<?php

 class __module_admin_acsgp {
 	
 	public $urls = array(
 		'acsgp' => 'page_acsgp',
 	
 		'groups'   => "page_groups",
 		'accesses' => "page_accesses",
 		'modules'  => "page_modules",
 		'users'    => "page_users"
 	);
 	
 	public function page_acsgp($args) {
 		
 		
 		return drv(DISP)->fetch(array('acsgp/default.html', new KT_start_moduleName('admin')));
 	}
 	
 	/** 
 	 * GROUPS BEGIN
 	 */
 	
 	public function page_groups($args) { // Быдлокод
 		
 		    if(is_numeric($_GET['delete']) && $this->delete_group($_GET['delete'])) __kernel_api::redirect('?');
 		elseif(!empty($_POST['name'])      && $this->create_group($_POST['name'])) __kernel_api::redirect('?');
 		elseif(is_numeric($_GET['edit']) && !empty($_GET['name']) && $this->change_group_name($_GET['name'], $_GET['edit'])) __kernel_api::redirect('?');
 		
 		if(!isset($_GET['about'])) {
	 		$groups = drv(ACSGP)->getGroups();
	 		
	 		drv(DISP)->assign('groups', &$groups);
	 		
	 		drv(DISP)->assign('acsgp_body', drv(DISP)->fetch(array('acsgp/groups.html', new KT_start_moduleName('admin'))));
 		} else {
 			if(!empty($_POST['access_to_gp'])) {
 				drv(DB)->autoExecute('acsgp_access', array(
 					'acsgp_id' => $_GET['about'],
 					'access'   => $_POST['access_to_gp']
 				), DB_AUTOQUERY_INSERT);
 			} elseif(is_numeric($_GET['delete_from_grp'])) {
 				drv(DB)->query("DELETE FROM `acsgp_access` WHERE `acsgp_id` = ? AND `access` = ? LIMIT 1", array($_GET['about'], $_GET['delete_from_grp']));
 				__kernel_api::redirect("?about={$_GET['about']}");
 			}
 			
 			$group = drv(ACSGP)->getAccesses($_GET['about']);
 			$names = drv(ACSGP)->getAccessesNames(true, 'name');
 			
 			drv(DISP)->assign(array(
 				'group' => &$group,
 				'group_name' => drv(ACSGP)->getGroupById($_GET['about']),
 				'names' => &$names
 			));
 			
 			drv(DISP)->assign('acsgp_body', drv(DISP)->fetch(array('acsgp/groups_about.html', new KT_start_moduleName('admin'))));
 		}
 		return drv(DISP)->fetch(array('acsgp/default.html', new KT_start_moduleName('admin')));
 	}
 	
 	/**
 	 * Удалит роль и все её упоминания
 	 * 
 	 * @param int $access
 	 * @return bool
 	 */
 	private function delete_group($acsgp) {
 		drv(DB)->query("DELETE FROM `acsgp` WHERE `acsgp` = ? LIMIT 1;", array((int)$acsgp));
 		drv(DB)->query("UPDATE `users` SET `access` = NULL WHERE `access` = ?", array((int)$acsgp));
 		
 		return true;
 	}
 	
 	/**
 	 * Добавит новую запись в таблицу acsgp
 	 * 
 	 * @param string $name
 	 * @param int $access
 	 * @return bool
 	 */
 	private function create_group($name) {
 		drv(DB)->autoExecute('acsgp', array(
 			'name'	 => $name
 		), DB_AUTOQUERY_INSERT);
 		
 		return true;
 	}
 	
 	/**
 	 * Позволяет изменить название группы
 	 * 
 	 * @param string $name
 	 * @param int $access
 	 * @return bool
 	 */
 	private function change_group_name($name, $acsgp) {
 		drv(DB)->autoExecute('acsgp', array(
 			'name'	 => $name
 		), DB_AUTOQUERY_UPDATE, "`acsgp` = ".(int)$acsgp);
 		
 		return true;
 	}
 	
 	/**
 	 * GROUPS END 
 	 */
 	
 	
 	/**
 	 * ACCESS BEGIN
 	 */
 	
 	public function page_accesses($args) {
 		
 		    if(is_numeric($_GET['delete']) && $this->delete_access_name($_GET['delete'])) __kernel_api::redirect('?');
 		elseif(is_numeric($_POST['code']) && !empty($_POST['name']) && $this->create_access_name($_POST['name'], $_POST['code'])) __kernel_api::redirect('?');
 		elseif(is_numeric($_GET['edit']) && !empty($_GET['name']) && $this->change_access_name($_GET['name'], $_GET['edit'])) __kernel_api::redirect('?');
 		
 		drv(DISP)->assign('access_names', drv(ACSGP)->getAccessesNames(false));
 		drv(DISP)->assign('acsgp_body', drv(DISP)->fetch(array('acsgp/accesses.html', new KT_start_moduleName('admin'))));
 		
 		return drv(DISP)->fetch(array('acsgp/default.html', new KT_start_moduleName('admin')));
 	}
 	
 	/**
 	 * Удалит роль и все её упоминания
 	 * 
 	 * @param int $access
 	 * @return bool
 	 */
 	private function delete_access_name($access) {
 		drv(DB)->query("DELETE FROM `access_names` WHERE `access` = ? LIMIT 1", array((int)$access));
 		drv(DB)->query("DELETE FROM `acsgp_access` WHERE `access` = ? AND ISNULL(`access_name`) AND ISNULL(`module`)", array((int)$access));
 		drv(DB)->query("UPDATE `modules` SET `access` = NULL WHERE `access` = ?", array((int)$access));
 		
 		return true;
 	}
 	
 	/**
 	 * Добавит новую запись в таблицу access_names
 	 * 
 	 * @param string $name
 	 * @param int $access
 	 * @return bool
 	 */
 	private function create_access_name($name, $access) {
 		drv(DB)->autoExecute('access_names', array(
 			'access' => (int)$access,
 			'name'	 => $name
 		), DB_AUTOQUERY_INSERT);
 		
 		return true;
 	}
 	
 	/**
 	 * Позволяет изменить название роли
 	 * 
 	 * @param string $name
 	 * @param int $access
 	 * @return bool
 	 */
 	private function change_access_name($name, $access) {
 		drv(DB)->autoExecute('access_names', array(
 			'name'	 => $name
 		), DB_AUTOQUERY_UPDATE, "`access` = ".(int)$access);
 		
 		return true;
 	}
 	
 	
 	/**
 	 * ACCESS END
 	 */
 	
 	
 	/**
 	 * MODULES BEGIN
 	 */
 	public function page_modules($args) {
 		if(!empty($_GET['acsMap'])) return $this->page_module_acsMap(); // Управление картой доступа
 		elseif(!empty($_GET['toDefault'])) $this->handler_toDefault();  // Привести карту доступа для модуля в стандартный вид
 		
 		$access_names = drv(ACSGP)->getAccessesNames();
 		
 		// Обработчик формы
 		if($_POST['submit'] == "true")
 			$this->update_modules(&$access_names);
 		
 		$res = &drv(DB)->query('SELECT * FROM `modules`');
 		while($module = &$res->fetchRow(DB_FETCHMODE_ASSOC)) {
 			$installed_modules[$module['id']] = $module;
 			if(class_exists("__module_{$module['module_name']}_config")) {
 				$installed_modules[$module['id']]['config'] = true;
 				if(is_array(ginst($module['module_name'].'_config')->getAccessMap()))
 					$installed_modules[$module['id']]['accessMap'] = true;
 				else
 					$installed_modules[$module['id']]['accessMap'] = false;
 			} else {
 				$installed_modules[$module['id']]['config'] = $installed_modules[$module['id']]['accessMap'] = false;
 			}
 		}
 		
 		drv(DISP)->assign(array(
 			'installed_modules' => $installed_modules,
 			'access_names'      => &$access_names
 		));
 		
 		drv(DISP)->assign('acsgp_body', drv(DISP)->fetch(array('acsgp/modules.html', new KT_start_moduleName('admin'))));
 		
 		return drv(DISP)->fetch(array('acsgp/default.html', new KT_start_moduleName('admin')));
 	}
 	
 	public function page_module_acsMap() {
 		if(!class_exists('__module_'.$_GET['acsMap'].'_config', true)) exit();
 		
 		$res = &drv(DB)->query('SELECT * FROM `acsgp_access` WHERE `module` = ?', array($_GET['acsMap']));
 		while($acs = &$res->fetchRow(DB_FETCHMODE_ASSOC)) {
 			$access[$acs['acsgp_id']][$acs['access_name']] = $acs['access'];
 		}
 		
 		if($_POST['submit'] == "acsMap") return $this->handler_acsMap($access);
 		
 		drv(DISP)->assign(array(
 			'overwrited_access' => $access,
 			'default_access'    => ginst($_GET['acsMap'].'_config')->getAccessMap(),
 			'acsGroups'         => drv(ACSGP)->getGroups()
 		));
 		
 		drv(DISP)->assign('acsgp_body', drv(DISP)->fetch(array('acsgp/modules_about.html', new KT_start_moduleName('admin'))));
 		
 		return drv(DISP)->fetch(array('acsgp/default.html', new KT_start_moduleName('admin')));
 	}
 	
 	/**
 	 * Разбирает POST и выболняет обновление переопределений в БД. Используется в page_module_acsMap
 	 * 
 	 * @param $access
 	 * @return void
 	 */
 	private function handler_acsMap($access) {
 		
 		$defaults = ginst($_GET['acsMap'].'_config')->getAccessMap();
 		$groups   = drv(ACSGP)->getGroups(true);
 		
 		//exit("<pre>".print_r($_POST['acs'], true)."</pre>");
 		
 		foreach($defaults as $acs_name=>$DEFacs_val) {
 			//echo"<br />$acs_name: ";
 			foreach($groups as $grid=>$group_array) {
 				$acs_val = $_POST['acs'][$acs_name][$grid]=="on"?1:0;
 				
 				//echo"$grid({$access[$grid][$acs_name]})-$acs_val({$defaults[$acs_name][0]})-";
 				
 				if(isset($access[$grid][$acs_name]) && $access[$grid][$acs_name] != $acs_val) {
 					//echo"0<br />"; continue;
 					drv(DB)->query("DELETE FROM `acsgp_access` WHERE `access_name` = ? AND `module` = ? LIMIT 1", array($acs_name, $_GET['acsMap']));
 				} elseif($acs_val != $defaults[$acs_name][0] && isset($defaults[$acs_name])) {
 					//echo"1<br />"; continue;
 					drv(DB)->autoExecute('acsgp_access', array(
 						'acsgp_id'    => $grid,
 						'access'      => $acs_val,
 						'access_name' => $acs_name,
 						'module'      => $_GET['acsMap']
 					), DB_AUTOQUERY_INSERT);
 				}/* else {
 					echo"2<br />";
 				}*/
 				
 			}
 		}
 		
 		__kernel_api::redirect('?acsMap='.$_GET['acsMap']);
 		
 	}
 	
 	private function handler_toDefault() {
 		if(!class_exists('__module_'.$_GET['toDefault'].'_config', true)) exit();
 		
 		drv(DB)->query("DELETE FROM `acsgp_access` WHERE `module` = ?", array($_GET['toDefault']));
 		
 		__kernel_api::redirect('?acsMap='.$_GET['toDefault']);
 	}
 	
 	private function update_modules($access_names) {
 		$res = &drv(DB)->query('SELECT * FROM `modules`');
 		
 		while($row = &$res->fetchRow(DB_FETCHMODE_ASSOC)) {
 			$modules[$row['id']] = &$row;
 		}
 		
 		foreach($_POST['module'] as $module_id=>$array) {
 			$arr = false;
 			
 			if(is_array($access_names[$array['access']]) && $modules[$module_id]['access'] != $array['access'])
 				$arr['access'] = $array['access'];
 				
 			if($modules[$module_id]['active'] != ($array['active']=="on"?"1":"0"))
 				$arr['active'] = ($array['active']=="on"?"1":"0");
 				
 			if(is_array($arr) && is_array($modules[$module_id]))
 				drv(DB)->autoExecute('modules', $arr, DB_AUTOQUERY_UPDATE, "id = {$modules[$module_id]['id']}");
 			
 		}
 	}
 	
 	/**
 	 * MODULES END
 	 */
 	
 	/**
 	 * USERS BEGIN
 	 */
 	
 	
 	public function page_users($args) {
 		if($_POST['submit'] == "true") $this->handler_updateUser();
 		
 		$user_in_groups = &drv(DB)->getAll('SELECT acsgp FROM `users` WHERE `login` = ? LIMIT 1', array($_GET['about']));
 		
 		if(!is_array($user_in_groups[0]) || empty($_GET['about'])) {
 			
 			drv(DISP)->assign('acsgp_body', drv(DISP)->fetch(array('acsgp/users.html', new KT_start_moduleName('admin'))));
 		
 		} else {
 		
	 		$user_in_groups = $user_in_groups[0][0];
	 		$user_in_groups = explode("|", $user_in_groups);
	 		
	 		drv(DISP)->assign(array(
	 			'user_in_groups' => $user_in_groups,
	 			'groups'    => drv(ACSGP)->getGroups()
	 		));
	 		
	 		drv(DISP)->assign('acsgp_body', drv(DISP)->fetch(array('acsgp/user_about.html', new KT_start_moduleName('admin'))));
 		
 		}
 		
 		return drv(DISP)->fetch(array('acsgp/default.html', new KT_start_moduleName('admin')));
 	}
 	
 	private function handler_updateUser() {
 		$i=1;
 		foreach($_POST['acsgp'] as $grid=>$on) {
 			$save .= "{$grid}";
 			
 			if($i!=count($_POST['acsgp'])) $save .= "|";
 			
 			$i++;
 		}
 		
 		drv(DB)->autoExecute('users', array('acsgp'=>$save), DB_AUTOQUERY_UPDATE, "`login` = '{$_GET['about']}'");
 		
 	}
 	
 	/**
 	 * USERS END
 	 */
 	
 }